<?php

class PasscodesController extends AppController {
  //public $scaffold;
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session');
  public $name = 'Passcodes';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'Passcode.id' => 'asc'
            ));
  }


//admin and public version
  function admin_index() {
    $this->layout = "admin";
    $this->set("title_for_layout", "Passcodes for Islevow.");
    $this->set('passcodes', $this->paginate('Passcode'));
  }

  //admin
  function admin_add() {
    $this->layout = "admin";
    $this->loadModel('Role');
    $this->set('options', $this->Role->find('list', array('fields'=> array('Role.role_name','Role.role_name'), 'order'=>array('role_name'=>'asc')  )));
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }

  //admin
  function admin_edit($id = null) {
    $this->layout = "admin";
    $this->loadModel('Role');
    $this->set('options', $this->Role->find('list', array('fields'=> array('Role.role_name','Role.role_name'), 'order'=>array('role_name'=>'asc')  )));
    $this->Passcode->id = $id;
    if ($this->request->is('get')) {
      $this->request->data = $this->Passcode->read();
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

  private function _processAction($dataIn, $action='add', $id=null) {
      $data = $this->_processRequestData($dataIn);
      $this->Passcode->set($data);
      if ($this->Passcode->validates()) {
        if ($this->Passcode->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index'));
        }
      } else {
        if($action!=='add') {
          $data['Passcode']['id']=$id;
        }
        $this->request->data['Passcode'] = $data['Passcode'];
        $this->set('errors', $this->Passcode->validationErrors);
      }
      if($action==='add') {
        $this->render('admin_add');
      } else {
        $this->render('admin_edit');
      }
  }
  
  function admin_delete($id) {
    $this->layout = "admin";
    //http://book.cakephp.org/2.0/en/models/deleting-data.html
    if ($this->Passcode->delete($id, true)) {
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }

}

?>
